#!/usr/bin/env python
#coding=utf-8
#dujie

from __future__ import division
import time
import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
from define import BASE_DIR,BLACK_LIST,route_key as route_list
sys.path.append(BASE_DIR)

from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort


class api_ftss_week(abstract_cron) :


    noLock = True   #是否生成脚本锁文件
    selectTable = 'sdb_statistics_api_ftss_day'
    insertTable = 'sdb_statistics_api_ftss_week'

    def __init__(self) :
        super(api_ftss_week,self).__init__(__file__)
        self.lastWeek = dateTypeInterval('last_week')
        self.currentWeek = dateTypeInterval('week')
        curWeekNum = sec2str('%W')
        lastWeekNum = sec2str('%W',time.time()-7*24*3600)
        self.dateIdent = '(第%s周)%s/%s' % (curWeekNum,self.currentWeek[0],self.currentWeek[1])
        self.weekFormat = '(第%s周)%s/%s' % (lastWeekNum,self.lastWeek[0],self.lastWeek[1])



    def boot(self,timestamp=[]) :
#        self.preBoot()

        sql = self.getSelectSql(timestamp)
        row = self.db.select(sql)

        if row :
            self.writeSql(sql,'succ','select')
            for v in row :
                v['week'] = self.weekFormat
                v['calltime'] = str2sec(self.lastWeek[1],format='%Y-%m-%d')-1*24*3600
                if v['api_sum'] > 0:
                    v['api_ftss'] = round(v['api_succ_once'] / v['api_sum'],5)
                else:
                    v['api_ftss'] = 1.00000
                #数据过滤
                self.filterItems(v)

            #批量插入
            self.doBatchExec()
        else :
            self.writeSql(sql,'fail','select')
        self.sufBoot()
        print 'ok'


    def getSelectSql(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        sql  = ' SELECT `api`,SUM(`retry_count`) AS retry_count,SUM(`api_succ_once`) AS api_succ_once,SUM(`api_sum`) AS api_sum,SUM(`api_ftss`) AS api_ftss,`calltime`'
        sql += ' FROM ' + self.selectTable
        sql += ' WHERE ' + self.db._filter(timeFilter)
        sql += ' GROUP BY `api`'
        return sql


    def getTimeFilter(self,timestamp=[]) :
        keyFilter = {}
        time_begin = str2sec(self.lastWeek[0],'%Y-%m-%d')
        time_end = str2sec(self.lastWeek[1],'%Y-%m-%d')+1*24*3600
#        time_begin = str2sec('2011-5-26','%Y-%m-%d')
#        time_end = str2sec('2011-6-01','%Y-%m-%d')
        keyFilter['calltime|between'] = timestamp and timestamp or [time_begin,time_end]
        return keyFilter

    def insertKeys(self) :
        return ['api','retry_count','api_succ_once','api_sum','api_ftss','week','calltime']



if __name__ == '__main__' :
    obj = api_ftss_week()
    obj.boot()




